package com.xixilala.video.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import kotlin.math.max

object ImageUtil {

    fun getAdaptedBitmap(context: Context, measuredWidth:Int, measuredHeight:Int): Bitmap? {

        val imageOrdinaryWidth: Int
        val imageOrdinaryHeight: Int

        val bitmapOptions = BitmapFactory.Options()
        val open = context.assets.open("image.png")
        val rect = Rect()
        BitmapFactory.decodeStream(open, rect, bitmapOptions.apply {
            inJustDecodeBounds = true // ==true bm返回空，宽高会放在 Options中
        })

        imageOrdinaryWidth = bitmapOptions.outWidth
        imageOrdinaryHeight = bitmapOptions.outHeight

        val rate = if (imageOrdinaryWidth>measuredWidth) {
            if(imageOrdinaryHeight>measuredHeight) {
                max(imageOrdinaryHeight / measuredHeight, imageOrdinaryWidth / measuredWidth)
            } else {
                imageOrdinaryWidth / measuredWidth
            }
        } else {
            if(imageOrdinaryHeight>measuredHeight) {
                imageOrdinaryHeight / measuredHeight
            } else {
                1
            }
        }

        open.reset()
        val bmReal = BitmapFactory.decodeStream(open, rect, bitmapOptions.apply {
            inJustDecodeBounds = false
            inSampleSize = rate
        })
        return bmReal
    }
}